package com.perkinelmer.housecall.client.activities.selectpatient;

import java.util.List;

import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.perkinelmer.housecall.client.activities.patientdetails.PatientDetailsActivity;
import com.perkinelmer.housecall.client.activity.ActivityManager;
import com.perkinelmer.housecall.client.activity.NoParameterActivity;
import com.perkinelmer.housecall.client.activity.NoParameters;
import com.perkinelmer.housecall.client.model.Patient;

public class SelectPatientActivity extends NoParameterActivity {

	private static final String WIDTH = "155px";
	private static final String HEIGHT = "155px";
	private static final int ROW_SIZE = 2;
	
	ActivityManager manager;
	public static final ActivityId<NoParameters> ID = ActivityId.make("SelectPatient");
	
	public SelectPatientActivity(ActivityManager manager) {
		this.manager = manager;
	}

	@Override
	public ActivityId<NoParameters> getId() {
		return ID;
	}

	@Override
	public void stop() {}
	
	@Override
	public void start(Panel panel) {
		VerticalPanel contentPanel = new VerticalPanel();
		
		FlexTable table = new FlexTable();
		addPatientsToTable(table, HardcodedPatients.getAllPatients());

		contentPanel.add(createTitle());
		contentPanel.add(table);
		
		panel.add(contentPanel);
	}
	
	private Label createTitle() {
		Label title = new Label("House Call");
		Style style = title.getElement().getStyle();
		
		style.setProperty("textAlign", "center");
		
		return title;
	}
	
	private void addPatientsToTable(FlexTable table, List<Patient> patients) {
		int column = 0;
		int row = 0;
		for(Patient patient : patients) {
			VerticalPanel panel = new VerticalPanel();
			PushButton button = createPatientButton(patient);
			Label name = new Label(patient.name);
			Style style = name.getElement().getStyle();
			
			style.setProperty("textAlign", "center");			
			panel.add(button);
			panel.add(name);
			table.setWidget(row, column, panel);
						
			column++;
			if(column >= ROW_SIZE) {
				column = 0;
				row++;
			}
		}
	}
	
	private PushButton createPatientButton(final Patient patient) {
		Image image = new Image(patient.imageUrl);
		image.setSize(WIDTH, HEIGHT);
		
		PushButton button = new PushButton(image);
		button.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				manager.gotoActivity(PatientDetailsActivity.ID, patient);
			}
		});
		
		return button;
	}

}
